/*
 *  Arduino type of routine to mesure timer
 *
 *  initMillis() will initalize timer1
 *  getMillis() will return a 32bit value containing current time
 *  resetMillis() will reset the global variable
 *  runMillis() will be called by the interrupt handles for timer1 interrups
 *
 */
#include <p18cxxx.h>

unsigned long millis;

// 12000 = 0x2EE0, 0xffff-0x2ee0 = 0xd11f
#define CORRECTION 4
#define MILLILOW  0x1f-CORRECTION
#define MILLIHIGH 0xd1  // must be written first


void initMillis(void)
{
// initalize Timer setup, timer is 1/2 processor clock = 6mhz
    T0CONbits.T08BIT=0; // run 16 bits counter
    T0CONbits.T0CS=0; // source internal clock
    T0CONbits.PSA=1; // do not use prescale
    T0CONbits.TMR0ON=1;

// initalize timer interrupt
    INTCONbits.TMR0IE=1;
    INTCONbits.GIE=1;
    INTCONbits.GIEH=1;

    // to test
    TRISCbits.RC0=0;

}

unsigned long getMillis(void)
{
    return millis;
}

void resetMillis(void)
{
    millis=0;
}

void runMillis(void)
{
    TMR0H=MILLIHIGH;
    TMR0L=MILLILOW;
    millis++;
//    LATCbits.LATC0=!LATCbits.LATC0;
}
